package hibernate;


import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;

import api.Person;

public class DAO<E> {
	/**
	    * Retrieves the list of all the objects from DB.
	    * 
	    * @return list of objects
	    */
	   @SuppressWarnings("unchecked")
      public List<E> loadAll()
	   {
		   Session session = null;
		      List<E> objects = new ArrayList<E>();
		      try
		      {
		         session = HibernateUtil.getSessionFactory().openSession();
		         objects = session.createCriteria(Person.class).list();
		      }
		      catch (Exception e)
		      {
		         e.printStackTrace();
		      }
		      finally
		      {
		         if (session != null && session.isOpen())
		         {
		            session.close();
		         }
		      }
		      return objects;
	   }
	   
	   /**
	    * Stores new object in DB. 
	    * 
	    * @param object to be stored
	    */
	   public Long add(E object)
	   {
		   Long id=0l;
			  Session session = null;
		      try
		      {
		         session = HibernateUtil.getSessionFactory().openSession();
		         session.beginTransaction();
		         id=(Long) session.save(object);                 
		         session.getTransaction().commit();
		      }
		      catch (Exception e)
		      {
		         e.printStackTrace();
		      }
		      finally
		      {
		         if (session != null && session.isOpen())
		         {
		            session.close();
		         }
		      }
		      return id;
	   }
	   
	   /**
	    * Updates specified object in DB.
	    * 
	    * @param object to be updated
	    */
	   public void edit(E object)
	   {
		   Session session = null;
		      try
		      {
		         session = HibernateUtil.getSessionFactory().openSession();
		         session.beginTransaction();
		         session.saveOrUpdate(object);
		         session.getTransaction().commit();
		      }
		      catch (Exception e)
		      {
		         e.printStackTrace();
		      }
		      finally
		      {
		         if (session != null && session.isOpen())
		         {
		            session.close();
		         }
		      }
	   }
	   
	   /**
	    * Deletes specified object from DB.
	    * 
	    * @param object to be deleted
	    */
	   public void delete(E object)
	   {
		   Session session = null;
		      try
		      {
		         session = HibernateUtil.getSessionFactory().openSession();
		         session.beginTransaction();
		         session.delete(object);
		         session.getTransaction().commit();
		      }
		      catch (Exception e)
		      {
		         e.printStackTrace();
		      }
		      finally
		      {
		         if (session != null && session.isOpen())
		         {
		            session.close();
		         }
		      }
	   }
}
